<?php

class DB_Functions {

    private $db;
    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
		require_once 'CL_Functions.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {
        
    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
		$host = $_SERVER['REMOTE_ADDR'];
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at, activated,last_host) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW(), 0,'$host')");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
			$user = mysql_fetch_assoc($result);
            // return user details
			$func = new CL_Functions();
			$func->regEmail($user['name'],$user['email'],$user['created_at'],$user['unique_id']);
			$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
			$id = $result['uid'];
			$hostname = $_SERVER["REMOTE_ADDR"];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
				mysql_query("UPDATE users SET last_host = '$hostname' WHERE uid ='$id'");
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }
	
	public function activateAccount($uid){
		$result = mysql_query("SELECT activated FROM users WHERE unique_id = '$uid'");
		$activated = mysql_fetch_assoc($result);
		if ($activated['activated'] == "1"){
			return "activated";
		} else{
			$result = mysql_query("UPDATE users SET activated = '1'");
			return true;
		}
	}
	
	public function getUser($email){
		$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
		if (mysql_num_rows($result) == 0){
			return false;
		} else {
			return mysql_fetch_array($result);
		}
	}

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }
	public function getMOTD(){
		$result = mysql_query("SELECT * FROM motd ORDER BY uid DESC");
		if (mysql_num_rows($result) > 0){
			$row = mysql_fetch_assoc($result);
			return $row;
		} else {
			return NULL;
		}
		
	}
	public function storeDevice($uid, $serial, $model, $version){
		$result = mysql_query("SELECT * FROM handsets WHERE unique_id = '$uid' AND serial = '$serial'");
		if (mysql_num_rows($result) > 0){
			$result = mysql_query("UPDATE handsets SET serial = '$serial', last_update = NOW(), version = '$version', model = '$model' WHERE unique_id = '$uid' AND serial = '$serial'") or die(mysql_error());
			if ($result){
				return true;
			} else{
				return false;
			}
		}
		else{
			$result = mysql_query("INSERT INTO handsets (uid, unique_id, serial, model,last_update, version) VALUES ('','$uid','$serial','$model',NOW(),'$version')") or die(mysql_error());
			if ($result){
				return true;
			} else{
				return false;
			}
		}
	}
	public function updateLocation($uid, $serial, $long, $lat, $alt){
		$result = mysql_query("SELECT * FROM handsets WHERE unique_id = '$uid' AND serial = '$serial'");
		if (mysql_num_rows($result) > 0){
			$result = mysql_query("UPDATE handsets SET last_update = NOW(), longtitude = '$long', latitude = '$lat', altitude = '$alt' WHERE unique_id = '$uid' AND serial = '$serial'") or die(mysql_error());
			if ($result){
				return true;
			} else{
				return false;
			}
		}
		else{
			return false;
		}
	}

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>
